#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
调试图片加载问题
"""

from database import template_dao
from pathlib import Path

def debug_templates():
    """调试模板数据"""
    print("🔍 调试模板数据...")
    
    templates = template_dao.get_all_templates()
    
    for template in templates:
        template_dict = dict(template)
        print(f"\n模板ID {template_dict['id']}:")
        print(f"  名称: {template_dict['name']}")
        print(f"  尺寸: {template_dict['width']} x {template_dict['height']}")
        print(f"  图片路径: {template_dict.get('image_path', 'None')}")
        print(f"  原始文件名: {template_dict.get('original_filename', 'None')}")
        
        # 检查文件是否存在
        image_path = template_dict.get('image_path')
        if image_path:
            file_path = Path(image_path) if Path(image_path).is_absolute() else Path('uploads') / image_path
            print(f"  实际路径: {file_path}")
            print(f"  文件存在: {file_path.exists()}")
            
            if file_path.exists():
                try:
                    from PIL import Image
                    with Image.open(file_path) as img:
                        print(f"  PIL读取: ✅ {img.size} {img.mode} {img.format}")
                except Exception as e:
                    print(f"  PIL读取: ❌ {e}")

def test_direct_access():
    """测试直接访问XL.tif"""
    print("\n🖼️ 测试直接访问XL.tif...")
    
    tif_file = Path("XL.tif")
    print(f"XL.tif存在: {tif_file.exists()}")
    
    if tif_file.exists():
        print(f"文件大小: {tif_file.stat().st_size / 1024 / 1024:.2f} MB")
        
        try:
            from PIL import Image
            with Image.open(tif_file) as img:
                print(f"PIL读取成功: {img.size} {img.mode} {img.format}")
                
                # 测试转换为PNG
                from io import BytesIO
                img_io = BytesIO()
                
                # 转换模式
                if img.mode not in ['RGB', 'L']:
                    img = img.convert('RGB')
                
                # 创建缩略图
                img.thumbnail((800, 800), Image.Resampling.LANCZOS)
                img.save(img_io, 'PNG')
                
                print(f"PNG转换成功: {len(img_io.getvalue())} bytes")
                
        except Exception as e:
            print(f"PIL处理失败: {e}")

if __name__ == '__main__':
    debug_templates()
    test_direct_access()
